import React, { useState, useEffect } from 'react';
import SearchInput from './components/SearchInput';
import WeatherCard from './components/WeatherCard';
import ErrorMessage from './components/ErrorMessage';
import InstallPrompt from './components/InstallPrompt';
import weatherManager from './services/weatherManager';
import './App.css';

function App() {
  const [weatherData, setWeatherData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [searchedCity, setSearchedCity] = useState('');
  const [suggestions, setSuggestions] = useState([]);

  // 组件挂载时获取建议城市
  useEffect(() => {
    const cachedCities = weatherManager.getCachedCities();
    setSuggestions(cachedCities);
  }, []);

  // 搜索天气信息
  const handleSearch = async (cityName) => {
    if (!cityName.trim()) return;

    setIsLoading(true);
    setError(null);
    setSearchedCity(cityName);

    try {
      const data = await weatherManager.getWeather(cityName);
      setWeatherData(data);
      
      // 更新建议列表
      const updatedSuggestions = weatherManager.getCachedCities();
      setSuggestions(updatedSuggestions);
      
    } catch (err) {
      setError(err.message);
      setWeatherData(null);
    } finally {
      setIsLoading(false);
    }
  };

  // 刷新天气信息
  const handleRefresh = async () => {
    if (!searchedCity) return;

    setIsLoading(true);
    setError(null);

    try {
      const data = await weatherManager.refreshWeather(searchedCity);
      setWeatherData(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  // 重试获取天气信息
  const handleRetry = () => {
    if (searchedCity) {
      handleSearch(searchedCity);
    }
  };

  // 处理建议点击
  const handleSuggestionClick = (cityName) => {
    handleSearch(cityName);
  };

  // 获取缓存统计信息
  const cacheStats = weatherManager.getCacheStats();

  return (
    <div className="app">
      <div className="app-container">
        {/* 应用头部 */}
        <header className="app-header">
          <h1 className="app-title">
            <span className="title-icon">🌤️</span>
            天气查询
          </h1>
          <p className="app-subtitle">
            实时获取全球城市天气信息
          </p>
          <InstallPrompt />
        </header>

        {/* 搜索区域 */}
        <div className="search-section">
          <SearchInput
            onSearch={handleSearch}
            isLoading={isLoading}
            suggestions={suggestions}
            onSuggestionClick={handleSuggestionClick}
          />
        </div>

        {/* 内容区域 */}
        <main className="app-main">
          {/* 加载状态 */}
          {isLoading && (
            <div className="loading-container">
              <div className="loading-spinner">🌀</div>
              <p className="loading-text">正在获取天气信息...</p>
            </div>
          )}

          {/* 错误信息 */}
          {error && !isLoading && (
            <ErrorMessage
              error={error}
              onRetry={handleRetry}
              cityName={searchedCity}
            />
          )}

          {/* 天气卡片 */}
          {weatherData && !isLoading && !error && (
            <WeatherCard
              weatherData={weatherData}
              onRefresh={handleRefresh}
              isLoading={isLoading}
            />
          )}

          {/* 欢迎信息 */}
          {!weatherData && !isLoading && !error && (
            <div className="welcome-container">
              <div className="welcome-icon">🌍</div>
              <h2 className="welcome-title">欢迎使用天气查询</h2>
              <p className="welcome-description">
                输入城市名称，即可获取实时天气信息
              </p>
              <div className="welcome-features">
                <div className="feature-item">
                  <span className="feature-icon">⚡</span>
                  <span>实时数据</span>
                </div>
                <div className="feature-item">
                  <span className="feature-icon">💾</span>
                  <span>智能缓存</span>
                </div>
                <div className="feature-item">
                  <span className="feature-icon">🎨</span>
                  <span>精美界面</span>
                </div>
              </div>
            </div>
          )}
        </main>

        {/* 应用底部 */}
        <footer className="app-footer">
          <div className="cache-info">
            <span className="cache-label">缓存状态:</span>
            <span className="cache-stats">
              {cacheStats.valid} 个有效缓存
            </span>
          </div>
       
        </footer>
      </div>
    </div>
  );
}

export default App;
